/**
 * 日志级别枚举
 */
export enum LogLevel {
    DEBUG = 0,
    INFO = 1,
    WARN = 2,
    ERROR = 3,
    NONE = 4 // 不输出任何日志
}

/**
 * 日志配置接口
 */
export interface LoggerConfig {
    /** 当前日志级别，低于此级别的日志不会输出 */
    level: LogLevel
    /** 是否启用时间戳 */
    enableTimestamp: boolean
    /** 是否启用彩色输出 */
    enableColors: boolean
    /** 日志前缀 */
    prefix: string
    /** 是否在生产环境输出日志 */
    enableInProduction: boolean
}

/**
 * 日志项接口
 */
export interface LogEntry {
    level: LogLevel
    message: string
    timestamp: Date
    data?: any[]
}

/**
 * 轻量级日志工具类
 * 仿照BrowserLogger设计，支持日志级别控制和生产环境配置
 */
export class Logger {
    private config: LoggerConfig
    private isProduction: boolean

    // 日志级别对应的样式配置
    private readonly levelStyles = {
        [LogLevel.DEBUG]: {
            color: '#6B7280',
            background: '#F9FAFB',
            label: 'DEBUG',
            consoleMethod: 'debug' as const
        },
        [LogLevel.INFO]: {
            color: '#0EA5E9',
            background: '#E0F2FE',
            label: 'INFO',
            consoleMethod: 'info' as const
        },
        [LogLevel.WARN]: {
            color: '#F59E0B',
            background: '#FEF3C7',
            label: 'WARN',
            consoleMethod: 'warn' as const
        },
        [LogLevel.ERROR]: {
            color: '#EF4444',
            background: '#FEE2E2',
            label: 'ERROR',
            consoleMethod: 'error' as const
        }
    }

    constructor(config: Partial<LoggerConfig> = {}) {
        // 默认配置
        this.config = {
            level: LogLevel.INFO,
            enableTimestamp: true,
            enableColors: true,
            prefix: '[Logger]',
            enableInProduction: false,
            ...config
        }

        // 检测是否为生产环境
        this.isProduction = import.meta.env.PROD || !this.isDevelopment()
    }

    /**
     * 检测是否为开发环境
     */
    private isDevelopment(): boolean {
        try {
            return (
                typeof window !== 'undefined' &&
                (window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname.includes('dev'))
            )
        } catch {
            return false
        }
    }

    /**
     * 检查是否应该输出日志
     */
    private shouldLog(level: LogLevel): boolean {
        // 检查日志级别
        if (level < this.config.level) {
            return false
        }

        // 生产环境检查
        if (this.isProduction && !this.config.enableInProduction) {
            return false
        }

        return true
    }

    /**
     * 格式化时间戳
     */
    private formatTimestamp(): string {
        if (!this.config.enableTimestamp) {
            return ''
        }

        const now = new Date()
        const time = now.toLocaleTimeString('zh-CN', {
            hour12: false,
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            fractionalSecondDigits: 3
        })
        return `[${time}]`
    }

    /**
     * 格式化日志消息
     */
    private formatMessage(level: LogLevel, message: string): string {
        const timestamp = this.formatTimestamp()
        const style = this.levelStyles[level as keyof typeof this.levelStyles]
        const levelLabel = style?.label || 'UNKNOWN'
        const prefix = this.config.prefix

        return `${timestamp} ${prefix} [${levelLabel}] ${message}`.trim()
    }

    /**
     * 输出日志到控制台
     */
    private output(level: LogLevel, message: string, ...data: any[]): void {
        if (!this.shouldLog(level)) {
            return
        }

        // NONE级别不输出任何日志
        if (level === LogLevel.NONE) {
            return
        }

        const formattedMessage = this.formatMessage(level, message)
        const style = this.levelStyles[level as keyof typeof this.levelStyles]
        if (!style) {
            return
        }
        const consoleMethod = console[style.consoleMethod]

        if (this.config.enableColors && typeof window !== 'undefined') {
            // 浏览器环境，使用彩色输出
            const styleStr = `
        color: ${style.color}; 
        background: ${style.background}; 
        padding: 2px 6px; 
        border-radius: 3px; 
        font-weight: bold;
      `
            consoleMethod(`%c${formattedMessage}`, styleStr, ...data)
        } else {
            // Node.js环境或不支持彩色，使用普通输出
            consoleMethod(formattedMessage, ...data)
        }
    }

    /**
     * DEBUG 级别日志
     */
    debug(message: string, ...data: any[]): void {
        this.output(LogLevel.DEBUG, message, ...data)
    }

    /**
     * INFO 级别日志
     */
    info(message: string, ...data: any[]): void {
        this.output(LogLevel.INFO, message, ...data)
    }

    /**
     * WARN 级别日志
     */
    warn(message: string, ...data: any[]): void {
        this.output(LogLevel.WARN, message, ...data)
    }

    /**
     * ERROR 级别日志
     */
    error(message: string, ...data: any[]): void {
        this.output(LogLevel.ERROR, message, ...data)
    }

    /**
     * 动态设置日志级别
     */
    setLevel(level: LogLevel): void {
        this.config.level = level
    }

    /**
     * 获取当前日志级别
     */
    getLevel(): LogLevel {
        return this.config.level
    }

    /**
     * 更新配置
     */
    updateConfig(config: Partial<LoggerConfig>): void {
        this.config = { ...this.config, ...config }
    }

    /**
     * 获取当前配置
     */
    getConfig(): LoggerConfig {
        return { ...this.config }
    }

    /**
     * 创建子Logger（带有特定前缀）
     */
    createChild(prefix: string): Logger {
        return new Logger({
            ...this.config,
            prefix: `${this.config.prefix}:${prefix}`
        })
    }

    /**
     * 批量日志输出（用于调试复杂对象）
     */
    group(title: string, callback: () => void): void {
        if (!this.shouldLog(LogLevel.INFO)) {
            return
        }

        console.group(this.formatMessage(LogLevel.INFO, title))
        try {
            callback()
        } finally {
            console.groupEnd()
        }
    }

    /**
     * 表格形式输出数据（适合数组对象）
     */
    table(data: any[], message?: string): void {
        if (!this.shouldLog(LogLevel.INFO)) {
            return
        }

        if (message) {
            this.info(message)
        }
        console.table(data)
    }

    /**
     * 性能计时开始
     */
    time(label: string): void {
        if (!this.shouldLog(LogLevel.DEBUG)) {
            return
        }
        console.time(this.formatMessage(LogLevel.DEBUG, `Timer: ${label}`))
    }

    /**
     * 性能计时结束
     */
    timeEnd(label: string): void {
        if (!this.shouldLog(LogLevel.DEBUG)) {
            return
        }
        console.timeEnd(this.formatMessage(LogLevel.DEBUG, `Timer: ${label}`))
    }
}

/**
 * 创建默认Logger实例
 */
export const createLogger = (config?: Partial<LoggerConfig>): Logger => {
    return new Logger(config)
}

/**
 * 预配置的Logger实例
 */

// 开发环境Logger（输出所有级别）
export const devLogger = createLogger({
    level: LogLevel.DEBUG,
    enableTimestamp: true,
    enableColors: true,
    prefix: '[Dev]',
    enableInProduction: false
})

// 生产环境Logger（只输出错误和警告）
export const prodLogger = createLogger({
    level: LogLevel.WARN,
    enableTimestamp: false,
    enableColors: false,
    prefix: '[Prod]',
    enableInProduction: true
})

// 默认Logger实例
export const logger = createLogger({
    level: LogLevel.INFO,
    enableTimestamp: true,
    enableColors: true,
    prefix: '[嘉虹健康]',
    enableInProduction: false
})

export default logger
